package com.black.app.service.impl.my;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.my.AppMyUserinfo;
import com.black.app.domain.resp.my.MyUserPostResp;
import com.black.app.mapper.my.AppMyDynamicImgOrVideoMapper;
import com.black.app.mapper.my.AppMyUserdynamicMapper;
import com.black.app.service.my.AppMyUserdynamicService;
import com.black.app.service.my.AppMyUserinfoService;
import com.black.app.mapper.my.AppMyUserinfoMapper;
import com.black.common.constant.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
* @author 18494
* @description 针对表【app_my_userinfo(用户信息表)】的数据库操作Service实现
* @createDate 2024-10-23 20:49:29
*/
@Service
public class AppMyUserinfoServiceImpl extends ServiceImpl<AppMyUserinfoMapper, AppMyUserinfo>
    implements AppMyUserinfoService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AppMyUserdynamicMapper appMyUserdynamicMapper;

    @Autowired
    private AppMyUserinfoMapper appMyUserinfoMapper;

    @Autowired
    private AppMyDynamicImgOrVideoMapper appMyDynamicImgOrVideoMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removePost(Long[] id) {
        if(Objects.isNull(id) || id.length == 0){
            throw new RuntimeException("id不存在");
        }

        this.redisTemplate.execute(new SessionCallback<Void>() {
            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                // 开启redis事务
                operations.multi();

                // 循环删除，因为数据量不大, 时间复杂度O(n), 事务问题
                try {
                    for (Long id : id) {
                        MyUserPostResp entity = appMyUserdynamicMapper.getById(id);
                        if (Objects.nonNull(entity)) {
                            appMyUserdynamicMapper.deleteById(id);
                            appMyDynamicImgOrVideoMapper.deleteByNamicId(id);
                            operations.delete(CacheConstants.APP_FIND_ZHANGZHISHI_KEY + entity.getId());
                        }
                    }
                    // 提交redis事务
                    operations.exec();
                }catch (Exception e){
                    // 回滚redis事务
                    operations.discard();
                    throw e;
                }
                return null;
            }
        });

        return true;
    }

}




